package org.example.yunshu.demos.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.example.yunshu.demos.constant.WebSocketTypeEnum;
import org.example.yunshu.demos.model.ResponseMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class OnlineManager {
    private ObjectMapper objectMapper = new ObjectMapper();
     private ConcurrentHashMap<Integer , WebSocketSession> map = new ConcurrentHashMap<>();
//     用户上线
    public void online(Integer userId , WebSocketSession session) throws IOException {
        log.info("用户: "+userId+"上线");
          if(map.containsKey(userId)){
              WebSocketSession oldSession = map.get(userId) ;
              ResponseMessage responseMessage = new ResponseMessage() ;
              responseMessage.setType(WebSocketTypeEnum.CLOSE.val);
              map.remove(userId);
              oldSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(responseMessage)));
          }
         map.put(userId , session) ;
    }
    // 连接发生异常/用户下线
    public void downLine(Integer userId ){
        if(map.containsKey(userId)){
         map.remove(userId) ;
        }
        log.info("用户: "+userId+" 下线");
    }

    // 通过userId获取session
    public WebSocketSession getSessionById(Integer userId){
        return map.getOrDefault(userId , null) ;
    }

}
